/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * listEmpresa.java
 *
 * Created on 29/11/2011, 14:16:49
 */
package visao;

import empresa.Empresa;
import fachada.FachadaBDR;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import util.CamposObrigatoriosException;
import util.ErroAcessoRepositorioException;

/**
 *
 * @author Administrador
 */
public class listEmpresa extends javax.swing.JFrame {

    public String[] titulos = new String[]{" # ", " Empresa ", " Razão Social ", " Status "};
    public DefaultTableModel defTable;
    public CadEmpresa cadastroEmpresa = new CadEmpresa();

    /** Creates new form listEmpresa */
    public listEmpresa() {
        try {
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();
            List<Empresa> listEmpresa = objfaFachadaBDR.listarEmpresa(" AND status_empresa = true order by id_empresa");

            // Setando a tabela
            this.defTable = atualizaLista(listEmpresa);
        } catch (ErroAcessoRepositorioException ex) {
            System.out.println(ex.getMessage());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

        initComponents();
        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagens/iconevisao.gif")).getImage());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton_Atualizar = new javax.swing.JButton();
        jButton_Editar = new javax.swing.JButton();
        jButton_Cadastrar = new javax.swing.JButton();
        jButton_Remover = new javax.swing.JButton();
        jLabel_DescricaoEmpresa = new javax.swing.JLabel();
        jTextField_Buscar = new javax.swing.JTextField();
        jButton_Buscar = new javax.swing.JButton();
        jLabel_Mensagem = new javax.swing.JLabel();

        setTitle("Empresa");
        setResizable(false);

        jTable1.setModel(this.defTable);
        jScrollPane1.setViewportView(jTable1);

        jButton_Atualizar.setText("Atualizar");
        jButton_Atualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AtualizarActionPerformed(evt);
            }
        });

        jButton_Editar.setText("Editar");
        jButton_Editar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_EditarActionPerformed(evt);
            }
        });

        jButton_Cadastrar.setText("Cadastrar");
        jButton_Cadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_CadastrarActionPerformed(evt);
            }
        });

        jButton_Remover.setText("Remover");
        jButton_Remover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_RemoverActionPerformed(evt);
            }
        });

        jLabel_DescricaoEmpresa.setText(" Empresa:");

        jButton_Buscar.setText("Buscar");
        jButton_Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_BuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jButton_Cadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Editar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14)
                        .addComponent(jButton_Atualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Remover, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 686, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jLabel_DescricaoEmpresa)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31)
                        .addComponent(jButton_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel_Mensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 655, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel_DescricaoEmpresa)
                    .addComponent(jTextField_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton_Buscar))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton_Cadastrar)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton_Atualizar)
                        .addComponent(jButton_Editar)
                        .addComponent(jButton_Remover)))
                .addGap(18, 18, 18)
                .addComponent(jLabel_Mensagem, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CadastrarActionPerformed
        // TODO add your handling code here:

        try {
            if (!this.cadastroEmpresa.isVisible()) {
                this.cadastroEmpresa = new CadEmpresa();
                this.cadastroEmpresa.setVisible(true);
            }

            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();
            List<Empresa> listEmpresa = objfaFachadaBDR.listarEmpresa(" AND status_empresa = true ");

            // Setando a tabela
            this.defTable = atualizaLista(listEmpresa);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            jTable1.revalidate();

        } catch (Exception ex) {
            jLabel_Mensagem.setText(ex.getMessage());
        }

    }//GEN-LAST:event_jButton_CadastrarActionPerformed

    private void jButton_EditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EditarActionPerformed
        // TODO add your handling code here:

        int idEmpresa = 0;
        try {
            // pegando a linha selecionada
            if (this.jTable1.getSelectedColumnCount() == 0) {
                throw new Exception("Favor selecionar uma Empresa");
            }

            // Pegando a linha que está selecionada
            int linha = this.jTable1.getSelectedRow();

            idEmpresa = (Integer) this.jTable1.getValueAt(linha, 0);

            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            Empresa objEmpresa = objFachadaBDR.procurarEmpresa(idEmpresa);


            // se a tela da Empresa ja estiver instanciada
            if (!this.cadastroEmpresa.isVisible()) {
                this.cadastroEmpresa = new CadEmpresa(objEmpresa.getIdEmpresa());
                this.cadastroEmpresa.setVisible(true);
            }
            // Listando as Empresas
            List<Empresa> listEmpresa = objFachadaBDR.listarEmpresa(" AND status_empresa = true ");

            // Setando a tabela
            this.defTable = atualizaLista(listEmpresa);


            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            // atualizando as Empresas
            jTable1.revalidate();

        } catch (Exception ex) {
            jLabel_Mensagem.setText(ex.getMessage());
        }


    }//GEN-LAST:event_jButton_EditarActionPerformed

    private void jButton_AtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AtualizarActionPerformed
        // TODO add your handling code here:

        try {
            // instanciando a fachada
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            // Listando os cargos
            List<Empresa> listEmpresa = objFachadaBDR.listarEmpresa(" AND status_empresa = true ");

            // Setando a tabela
            this.defTable = atualizaLista(listEmpresa);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            jTable1.revalidate();
        } catch (Exception ex) {
            jLabel_Mensagem.setText(ex.getMessage());
        }


    }//GEN-LAST:event_jButton_AtualizarActionPerformed

    private void jButton_RemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_RemoverActionPerformed
        // TODO add your handling code here:

        int cancelar = JOptionPane.showConfirmDialog(null, "Deseja Remover esta Empresa?");
        if (cancelar == JOptionPane.YES_OPTION) {
            try {
                // pegando a linha selecionada
                if (this.jTable1.getSelectedColumnCount() == 0 || this.jTable1.getSelectedColumnCount() > 1) {
                    throw new Exception("Favor selecionar uma Empresa");
                }

                int linha = this.jTable1.getSelectedRow();

                // recuperando o Cpf do funcionario
                int idEmpresa = (Integer) this.jTable1.getValueAt(linha, 0);

                // instanciando a fachada
                FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

                objFachadaBDR.removerEmpresa(idEmpresa);

                // Listando as Empresas
                List<Empresa> listEmpresa = objFachadaBDR.listarEmpresa(" AND status_empresa = true ");

                // Setando a tabela
                this.defTable = atualizaLista(listEmpresa);

                // Setando a nova listagem
                jTable1.setModel(this.defTable);

                jTable1.revalidate();

                jLabel_Mensagem.setText("Removido com sucesso!");

            } catch (Exception ex) {
                jLabel_Mensagem.setText(ex.getMessage());
            }
        }



    }//GEN-LAST:event_jButton_RemoverActionPerformed

    private void jButton_BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_BuscarActionPerformed
        // TODO add your handling code here:

        try {
            // instanciando a fachada
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            String descricaoEmpresa = jTextField_Buscar.getText().trim();
            
            // Listando as Empresas
            List<Empresa> listEmpresa = objFachadaBDR.procurarEmpresaPorDescricao(descricaoEmpresa);

            // Setando a tabela
            this.defTable = atualizaLista(listEmpresa);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);
            jTable1.revalidate();

        } catch (Exception ex) {
            jLabel_Mensagem.setText(ex.getMessage());
        }


    }//GEN-LAST:event_jButton_BuscarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new listEmpresa().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(listCargo.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public DefaultTableModel atualizaLista(List<Empresa> listEmpresa) {
        // Criando o objeto 
        Object[][] resposta = new Object[listEmpresa.size()][4];

        for (int i = 0; i < resposta.length; i++) {
            Empresa objEmpresa = listEmpresa.get(i);
            resposta[i][0] = objEmpresa.getIdEmpresa();
            resposta[i][1] = objEmpresa.getNomeFantasia();
            resposta[i][2] = objEmpresa.getRasaoSocial();
            resposta[i][3] = (objEmpresa.getStatusEmpresa()) ? "Ativo" : "Inativo";
        }

        // Setando a tabela
        return new DefaultTableModel(resposta, titulos);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_Atualizar;
    private javax.swing.JButton jButton_Buscar;
    private javax.swing.JButton jButton_Cadastrar;
    private javax.swing.JButton jButton_Editar;
    private javax.swing.JButton jButton_Remover;
    private javax.swing.JLabel jLabel_DescricaoEmpresa;
    private javax.swing.JLabel jLabel_Mensagem;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField_Buscar;
    // End of variables declaration//GEN-END:variables
}
